import { H3Event } from "h3"
import JWT from 'jsonwebtoken'
type JwrErr = {
  name: string,
  message: string,
  expiredAt?: number,
  date?: Date
}
export default defineEventHandler((e:H3Event)=>{
  const url = e.node.req.url ?? ''
  const filterArr = ['/api/session','/api/validation_codes'] //api过滤
  const state = !filterArr.some(ele=>url.startsWith(ele))
  if(url.startsWith('/api') && state){
    try{
      const jwt = e.node.req.headers.authorization ?? ''
      if(!jwt){
        return sendError(
          e,
          createError({ statusCode: 401, statusMessage: "令牌不存在，请登录后继续" })
        );
      }
      JWT.verify(jwt, process.env.JSON_SECRET,(err: JwrErr|null)=>{
        if(err){
          if(err.name === 'TokenExpiredError' && err.message==='jwt expired' ){
            return sendError( e, createError({ statusCode: 401, statusMessage: '令牌过期!', }) )
          }else{
            return createError({
              statusCode: 401,
              statusMessage: '令牌错误!',
            })
          }
        }
      })
    }catch(err){
      return sendError( e, createError({ statusCode: 400, statusMessage: "令牌验证出错！" }) )
    }
  }
})